package com.heima.controller;

import com.heima.annotation.GlobalInterceptor;
import com.heima.annotation.VerifyParam;
import com.heima.entity.constants.Constants;
import com.heima.entity.dto.SessionWebUserDto;
import com.heima.entity.dto.SysSettingsDto;
import com.heima.entity.dto.UploadResultDto;
import com.heima.entity.enums.FileCategoryEnums;
import com.heima.entity.enums.FileDelFlagEnums;
import com.heima.entity.enums.FileFolderTypeEnums;
import com.heima.entity.po.FileInfo;
import com.heima.entity.query.FileInfoQuery;
import com.heima.entity.vo.FileInfoVO;
import com.heima.entity.vo.PaginationResultVO;
import com.heima.entity.vo.ResponseVO;
import com.heima.service.FileInfoService;
import com.heima.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileInfoController extends CommonFileController{
    @Resource
    private FileInfoService fileInfoService;

    @RequestMapping("/loadDataList")
    @GlobalInterceptor
    public ResponseVO loadDataList(HttpSession session,
                                    FileInfoQuery query,String category){
        FileCategoryEnums categoryEnums = FileCategoryEnums.getByCode(category);
        if (categoryEnums != null){
            query.setFileCategory(categoryEnums.getCategory());
        }
//        SessionWebUserDto attribute = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        String userId = getUserInfoFromSession(session).getUserId();
        query.setUserId(userId);
        query.setOrderBy("folder_type desc , last_update_time desc");
        query.setDelFlag(FileDelFlagEnums.USING.getFlag());
        PaginationResultVO<FileInfo> listByPage = fileInfoService.findListByPage(query);

        fileInfoService.loadDataList(userId,query.getFileId());

        return getSuccessResponseVO(convert2PaginationVO(listByPage, FileInfoVO.class));
    }
    @RequestMapping("/uploadFile")
    @GlobalInterceptor(checkParams = true)
    public ResponseVO uploadFile(HttpSession session,
                                     String fileId,
                                     MultipartFile file,
                                     @VerifyParam(required = true) String fileName,
                                     @VerifyParam(required = true) String filePid,
                                     @VerifyParam(required = true) String fileMd5,
                                     @VerifyParam(required = true) Integer chunkIndex,
                                     @VerifyParam(required = true) Integer chunks){

        SessionWebUserDto userDto = getUserInfoFromSession(session);
        UploadResultDto uploadResultDto = fileInfoService.uploadFile(userDto, fileId, file, fileName, filePid, fileMd5, chunkIndex, chunks);
        return getSuccessResponseVO(uploadResultDto);
    }
    @RequestMapping("/getImage/{imageFolder}/{imageName}")
    @GlobalInterceptor(checkParams = true)
    public void getImage1(HttpServletResponse response,
                         @PathVariable("imageFolder") String imageFolder,
                         @PathVariable("imageName") String imageName){
        getImage(response,imageFolder,imageName);
    }

    @RequestMapping("/ts/getVideoInfo/{fileId}")
    @GlobalInterceptor(checkParams = true)
    public void getFile1(HttpServletResponse response,HttpSession session,
                          @PathVariable("fileId") String fileId){
        getFile(response,fileId,getUserInfoFromSession(session).getUserId());
    }
    ///getFile/{fileId}
    @RequestMapping("/getFile/{fileId}")
    @GlobalInterceptor(checkParams = true)
    public void getFile2(HttpServletResponse response,HttpSession session,
                         @PathVariable("fileId") String fileId){
        getFile(response,fileId,getUserInfoFromSession(session).getUserId());
    }
    @RequestMapping("/newFoloder")
    @GlobalInterceptor(checkParams = true)
    public ResponseVO newFolder(HttpSession session,
                          @VerifyParam(required = true) String filePid,
                          @VerifyParam(required = true) String fileName){
        FileInfo fileInfo = fileInfoService.newFolder(filePid, fileName, getUserInfoFromSession(session).getUserId());
        FileInfoVO fileInfoVO = new FileInfoVO();
        BeanUtils.copyProperties(fileInfo,fileInfoVO);
        return getSuccessResponseVO(fileInfoVO);
    }

    @RequestMapping("/getFolderInfo")
    @GlobalInterceptor(checkParams = true)
    public ResponseVO getFolderInfo(HttpSession session,String path){
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
//        FileInfo[] fileInfo = fileInfoService.getFolderInfo(webUserDto,path);

        return super.getFolderInfo(path, webUserDto.getUserId());
    }

    @RequestMapping("/rename")
    @GlobalInterceptor(checkParams = true)
    public ResponseVO rename(HttpSession session,String fileId,@VerifyParam(required = true) String fileName){
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
//        FileInfo[] fileInfo = fileInfoService.getFolderInfo(webUserDto,path);
        FileInfo fileInfo = fileInfoService.rename(webUserDto.getUserId(), fileId, fileName);
        FileInfoVO fileInfoVO = new FileInfoVO();
        BeanUtils.copyProperties(fileInfo,fileInfoVO);

        return getSuccessResponseVO(fileInfoVO);
    }


    @RequestMapping("/loadAllFolder")
    @GlobalInterceptor
    public ResponseVO loadAllFolder(HttpSession session,
                                    @VerifyParam(required = true) String filePid,
                                    String currentFileIds){
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setUserId(webUserDto.getUserId());
        fileInfoQuery.setFilePid(filePid);
        fileInfoQuery.setFolderType(FileFolderTypeEnums.FOLDER.getType());
//        if (!StringTools.isEmpty(currentFileIds)){
//            fileInfoQuery.setExcludeFileIdArray(currentFileIds.split(","));
//        }
        fileInfoQuery.setDelFlag(FileDelFlagEnums.USING.getFlag());
        fileInfoQuery.setOrderBy("create_time desc");
        List<FileInfo> fileInfoList = fileInfoService.findListByParam(fileInfoQuery);



        List<FileInfoVO> fileInfoVOS = new ArrayList<>();
//        BeanUtils.copyProperties(fileInfoList,fileInfoVOS);
        FileInfoVO fileInfoVO = null;
        for (FileInfo fileInfo : fileInfoList) {
            fileInfoVO = new FileInfoVO();
            BeanUtils.copyProperties(fileInfo,fileInfoVO);
            fileInfoVOS.add(fileInfoVO);
        }
        return getSuccessResponseVO(fileInfoVOS);
    }
    @RequestMapping("/changeFileFolder")
    @GlobalInterceptor
    public ResponseVO changeFileFolder(HttpSession session,
                                       @VerifyParam(required = true) String fileIds,
                                       @VerifyParam(required = true) String filePid){
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        fileInfoService.changeFileFolder(webUserDto.getUserId(),fileIds,filePid);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/createDownloadUrl/{fileId}")
    @GlobalInterceptor
    public ResponseVO createDownloadUrl(HttpSession session,
                                        @PathVariable("fileId") String fileId){
        return super.createDownloadUrl(fileId,getUserInfoFromSession(session).getUserId());
    }

    @RequestMapping("/download/{code}")
    @GlobalInterceptor
    public void downloadCode(@PathVariable("code") String code, HttpServletRequest request,HttpServletResponse response){
        try {
            super.download(request,response,code);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/delFile")
    @GlobalInterceptor
    public ResponseVO delFile(HttpSession session,
                              @RequestParam(value = "fileIds") String fileIds){
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        fileInfoService.delFile(webUserDto.getUserId(),fileIds);
        return getSuccessResponseVO(null);
    }

}
